<?php
namespace app\admin\logic;

use app\admin\code\AdminCode;
use app\admin\controller\Base;
use app\admin\model\AdminModel;
use app\admin\model\AuthModel;
use app\admin\model\RoleModel;
use app\admin\validate\LoginValidate;
use think\Session;
class LoginLogic extends BaseLogic
{
    protected $_no_login_auth = [
        'admin/login/index',
        'admin/login/login'
    ];//无需登录即可执行的节点

    /**
     * @param string $module 模块
     * @param string $controller 控制器
     * @param string $action 动作
     * @param callable $loginCallBack 需要执行登录时回调
     * @return bool
     */
    public function check_login($module = '',$controller = '',$action = '',$loginCallBack = null){
        $node = $module.'/'.$controller.'/'.$action;
        $admin_info = Base::get_admin_info();
        if(!in_array($node,$this->_no_login_auth) && $admin_info == false){//未登录
            if($loginCallBack){
                $loginCallBack();
            }else{
                return false;
            }
        }
    }

    /**
     * 登录逻辑
     * @return bool
     */
    public function login(){
        $validate = new LoginValidate();
        if($validate->validate($this->_param,__FUNCTION__) === false){
            $this->result = false;
            $this->err = $validate->getError();
            return false;
        }
        $adminInfo = $validate->user_data;
        unset($adminInfo['salt']);
        $role_model = new RoleModel();
        $auth = $role_model->findData(['id'=>$adminInfo['role_id']],'rule,is_super');
        if($auth['is_super']){
            $authModel = new AuthModel();
            $auth_list = $authModel->get_all_auth();
            $auth = [];
            foreach ($auth_list as $value){
                $auth[] = $value['id'];
            }
        }else{
            $auth = explode(',',$auth['rule']);
        }

        Session::set('admin.id',$adminInfo['id']);
        Session::set('admin.user_name',$adminInfo['user_name']);
        Session::set('admin.auth',$auth);
        Session::set('admin.is_super',$auth['is_super']);
        $this->result = true;
        return true;
    }
}
